<template>
  <div class="register-container">
    <Header title="注册" show-back />

    <div class="register-content">
      <div class="logo-section">
        <div class="logo">
          <van-icon name="cloud-o" size="60" color="#1989fa" />
        </div>
        <h1 class="app-title">创建账号</h1>
        <p class="app-desc">加入YY云盘，开启您的云存储之旅</p>
      </div>

      <van-form @submit="handleRegister" class="register-form">
        <van-cell-group inset>
          <van-field
            v-model="registerForm.email"
            name="email"
            label="邮箱"
            placeholder="请输入邮箱"
            left-icon="envelop-o"
            :rules="emailRules"
            autocomplete="email"
          />

          <van-field
            v-model="registerForm.nickname"
            name="nickname"
            label="昵称"
            placeholder="请输入昵称（可选）"
            left-icon="contact"
            :rules="nicknameRules"
            autocomplete="nickname"
          />

          <van-field
            v-model="registerForm.password"
            type="password"
            name="password"
            label="密码"
            placeholder="请输入密码"
            left-icon="lock"
            :rules="passwordRules"
            autocomplete="new-password"
          />

          <van-field
            v-model="confirmPassword"
            type="password"
            name="confirmPassword"
            label="确认密码"
            placeholder="请再次输入密码"
            left-icon="lock"
            :rules="confirmPasswordRules"
            autocomplete="new-password"
          />

          <van-field
            v-model="registerForm.verifyCode"
            name="verifyCode"
            label="验证码"
            placeholder="请输入验证码"
            left-icon="shield-o"
            :rules="verifyCodeRules"
          >
            <template #button>
              <van-button
                size="small"
                type="primary"
                :disabled="!canSendCode || codeCooldown > 0"
                :loading="sendingCode"
                @click="sendVerifyCode"
                class="verify-code-btn"
              >
                {{ codeCooldown > 0 ? `${codeCooldown}s` : '发送验证码' }}
              </van-button>
            </template>
          </van-field>
        </van-cell-group>

        <div class="register-actions">
          <van-button
            round
            block
            type="primary"
            native-type="submit"
            :loading="loading"
            loading-text="注册中..."
            class="register-button"
          >
            注册
          </van-button>
        </div>
      </van-form>

      <div class="bottom-links">
        <router-link to="/login" class="login-link">
          已有账号？立即登录
        </router-link>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed } from 'vue'
import { useRouter } from 'vue-router'
import { showToast } from 'vant'
import Header from '@/components/Header.vue'
import { register, sendVerifyCode as sendCode, type RegisterParams } from '@/api/user'

const router = useRouter()

const loading = ref(false)
const sendingCode = ref(false)
const codeCooldown = ref(0)
const confirmPassword = ref('')

const registerForm = reactive<RegisterParams>({
  email: '',
  password: '',
  nickname: '',
  verifyCode: ''
})

const canSendCode = computed(() => {
  return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(registerForm.email)
})

const emailRules = [
  { required: true, message: '请输入邮箱' },
  { pattern: /^[^\s@]+@[^\s@]+\.[^\s@]+$/, message: '请输入正确的邮箱格式' }
]

const nicknameRules = [
  { max: 20, message: '昵称长度不能超过20个字符' }
]

const passwordRules = [
  { required: true, message: '请输入密码' },
  { min: 6, message: '密码长度不能少于6位' },
  { max: 20, message: '密码长度不能超过20位' }
]

const confirmPasswordRules = [
  { required: true, message: '请确认密码' },
  {
    validator: (value: string) => {
      if (value !== registerForm.password) {
        return '两次输入的密码不一致'
      }
      return true
    }
  }
]

const verifyCodeRules = [
  { required: true, message: '请输入验证码' },
  { len: 6, message: '验证码为6位数字' }
]

const sendVerifyCode = async () => {
  if (!canSendCode.value) {
    showToast({
      type: 'fail',
      message: '请输入正确的邮箱'
    })
    return
  }

  try {
    sendingCode.value = true

    await sendCode({
      email: registerForm.email,
      type: 'register'
    })

    showToast({
      type: 'success',
      message: '验证码已发送'
    })

    codeCooldown.value = 60
    const timer = setInterval(() => {
      codeCooldown.value--
      if (codeCooldown.value <= 0) {
        clearInterval(timer)
      }
    }, 1000)

  } catch (error) {
    console.error('发送验证码失败:', error)

    let message = '发送验证码失败'
    if (error instanceof Error) {
      if (error.message.includes('邮箱已存在')) {
        message = '该邮箱已注册，请使用其他邮箱'
      } else if (error.message.includes('频繁')) {
        message = '发送过于频繁，请稍后再试'
      } else {
        message = error.message
      }
    }

    showToast({
      type: 'fail',
      message
    })
  } finally {
    sendingCode.value = false
  }
}

const handleRegister = async () => {
  if (confirmPassword.value !== registerForm.password) {
    showToast({
      type: 'fail',
      message: '两次输入的密码不一致'
    })
    return
  }

  try {
    loading.value = true

    await register(registerForm)

    showToast({
      type: 'success',
      message: '注册成功',
      onClose: () => {
        router.replace('/login')
      }
    })
  } catch (error) {
    console.error('注册失败:', error)

    let message = '注册失败'
    if (error instanceof Error) {
      if (error.message.includes('邮箱已存在')) {
        message = '该邮箱已注册'
      } else if (error.message.includes('验证码')) {
        message = '验证码错误或已过期'
      } else if (error.message.includes('网络')) {
        message = '网络连接失败，请检查网络'
      } else {
        message = error.message
      }
    }

    showToast({
      type: 'fail',
      message
    })
  } finally {
    loading.value = false
  }
}
</script>

<style scoped>
.register-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  flex-direction: column;
}

.register-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  padding: 20px;
  padding-top: 40px;
}

.logo-section {
  text-align: center;
  margin-bottom: 30px;
}

.logo {
  margin-bottom: 16px;
}

.app-title {
  font-size: 24px;
  font-weight: bold;
  color: white;
  margin: 0 0 8px 0;
}

.app-desc {
  font-size: 14px;
  color: rgba(255, 255, 255, 0.8);
  margin: 0;
}

.register-form {
  flex: 1;
}

.register-actions {
  padding: 24px 16px 16px;
}

.register-button {
  height: 44px;
  font-size: 16px;
  font-weight: 500;
}

.verify-code-btn {
  min-width: 90px;
  height: 32px;
}

.bottom-links {
  text-align: center;
  padding: 20px 0;
  margin-top: auto;
}

.login-link {
  color: rgba(255, 255, 255, 0.9);
  text-decoration: none;
  font-size: 14px;
}

.login-link:hover {
  color: white;
  text-decoration: underline;
}

:deep(.van-cell-group--inset) {
  margin: 0;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

:deep(.van-field__left-icon) {
  color: #1989fa;
}

:deep(.van-field__label) {
  color: #333;
  font-weight: 500;
}

:deep(.van-field__button) {
  padding-left: 8px;
}
</style>